import router from "@/router/index"
import requestUtil from '@/util/request'
import { ref } from 'vue'
import {useStore} from "@/store/piniaIndex"
import { ElMessage } from "element-plus"

const whiteList = ['/login'] // 白名单
router.beforeEach(async (to, from, next) => {
    const useStore1 = useStore();
    let token = useStore1.GET_TOKEN();
    if (whiteList.includes(to.path)) {
        next();
    } else if (token) {
        const menuList = ref(useStore1.menuList);
        if (menuList.value.length == 0) {
            let result = await requestUtil.get("crmMenu/list");
            if (result.data.code == 1) {
                const menuList = result.data.data;  // 更新响应式变量
                bindRoute(menuList);
                useStore1.SET_MENULIST(menuList)
                useStore1.SET_ROUTES_STATE(true)
                next(to.fullPath)
            } else {
                ElMessage({
                    type: 'error',
                    message: result.data.message,
                })
                window.sessionStorage.clear();
                next("/login")
            }
        } else {
            next();
        }
    } else {
        console.log("没有token的请求");
        window.sessionStorage.clear();
        next("/login")

    }

})


// 动态绑定路由
const bindRoute = (menuList) => {
    let newRoutes = router.options.routes;
    menuList.forEach(menu => {
        if (menu.children) {
            menu.children.forEach(m => {
                let route = menuToRoute(m, menu.name);
                if (route) {
                    newRoutes[0].children.push(route);
                }
            })
        }
    })
    // 重新添加到路由
    newRoutes.forEach(route => {
        router.addRoute(route)
    })
}

// 菜单对象转成路由对象
const menuToRoute = (menu, parentName) => {
    if (!menu.component) {
        return null;
    } else {
        let route = {
            name: menu.name,
            path: menu.path,
            meta: {
                parentName: parentName
            }
        }
        route.component = () => import('@/views/' + menu.component + '.vue');
        return route;
    }
}
